package com.sykj.springboot.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.sykj.springboot.common.contants.MapCatchs;
import com.sykj.springboot.common.entity.DataResponse;
import com.sykj.springboot.common.utils.RedisUtils;
import com.sykj.springboot.entity.SysUser;
import com.sykj.springboot.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

public class LoginFilter implements Filter{

	public Logger log = LoggerFactory.getLogger(getClass());
	public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
	//白名单
	String[] url = new String[]{
			"/login/*"
	};

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		log.info("自定义过滤器初始化");
		Filter.super.init(filterConfig);
	}

	@Override
	public void destroy() {
		log.info("自定义过滤器销毁");
		Filter.super.destroy();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		log.info("自定义过滤器---------------此处执行自己的业务");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		response.setContentType("text/html;charset=GBK");
		response.setContentType("text/html");
		String requestURL = req.getRequestURL().toString();
		//避免一个请求走两次
		if (!requestURL.contains("favicon.ico")){

			boolean check = this.check(url, requestURL);
			if (!check){
				String token = req.getHeader("token");
				System.out.println("token--------->"+token);
				DataResponse response1 = new DataResponse(DataResponse.STATUS_T, DataResponse.MSG_T);
				if (token == null){
					response.getWriter().write(JSON.toJSONString(response1));
					return;
				}else{
					SysUser user = (SysUser)RedisUtils.getObjFromRedis(token);
					if (user == null){
						response.getWriter().write(JSON.toJSONString(response1));
						return;
					}
				}
			}
			chain.doFilter(req, resp);

		}

	}

	public boolean check(String[] urls,String requestURI){
		String[] split = requestURI.split(":");
		String substring = split[2].substring(split[2].indexOf("/"));
		for (String url : urls) {
			if(PATH_MATCHER.match(url,substring)){
				return true;
			}
		}
		return false;
	}

}

